package lrscp.lib;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class StreamCmdProcotol {
    private static final String CMD_SYNC = "sync";
    InputStream mIs = null;
    OutputStream mOs = null;
    DataOutputStream mDos = null;
    DataInputStream mDis = null;

    public StreamCmdProcotol(InputStream is, OutputStream os) {
        mIs = is;
        mOs = os;
        mDos = new DataOutputStream(os);
        mDis = new DataInputStream(is);
    }

    /**
     * 
     * @param fd
     * @return time millis spent in transmission
     * @throws IOException
     */
    public long sendFile(File fd) throws IOException {
        if (!fd.exists()) {
            throw new IOException("file doesn't exits");
        }
        mDos.writeLong(fd.length());
        long startMillis = System.currentTimeMillis();
        IOUtils.copyLarge(new FileInputStream(fd), mOs, 0, fd.length());
        return Math.max(1, System.currentTimeMillis() - startMillis);
    }

    /**
     * 
     * @param fd
     * @return time millis spent in transmission
     * @throws IOException
     */
    public long receiveFile(File fd) throws IOException {
        if (fd == null) {
            throw new NullPointerException();
        }
        long length = mDis.readLong();
        long startMillis = System.currentTimeMillis();
        IOUtils.copyLarge(mIs, new FileOutputStream(fd), 0, length);
        return Math.max(1, System.currentTimeMillis() - startMillis);
    }

    public void sendCmd(String cmd) throws IOException {
        mDos.writeUTF(cmd);
    }

    public String readCmd() throws IOException {
        return mDis.readUTF();
    }
}
